using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// YH_ScreeningPlan
    ///</summary>
    [ApiExplorerSettings(GroupName = "YH")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class YH_ScreeningPlanController : CoreApiController
    {
        private readonly YH_ScreeningPlanService _service;
        /// <summary>
        /// YH_ScreeningPlan
        ///</summary>
        public YH_ScreeningPlanController(YH_ScreeningPlanService service)
        {
            _service = service;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(YH_ScreeningPlanController) + "_" + nameof(YH_ScreeningPlanController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetList(PagingModel<YH_ScreeningPlanDto> pagingQueryModel)
        {

            IPageModel<YH_ScreeningPlanDto> result = await _service.GetListForPC(pagingQueryModel);
            //拼接参与人员姓名
            result.PageData.ForEach(dto =>
            {
                var str = "";
                dto.YH_ScreeningPlanUser.ToList().ForEach(a =>
                {
                    str += a.UserText + ",";
                });
                if (str.Length > 0)
                    str = str.Substring(0, str.Length - 1);
                dto.Participant = str;

                dto.FrequencyText = _service.ShowFrequencyText(dto);

                dto.YH_ProjectAndDetail = new List<YH_ProjectAndDetail>();
                dto.YH_ScreeningPlanProject.ToList().ForEach(project =>
                {
                    project.YH_ScreeningPlanProDetail.ToList().ForEach(detail =>
                    {
                        dto.YH_ProjectAndDetail.Add(new YH_ProjectAndDetail()
                        {
                            ScreeningPlanId = dto.Id,
                            Project = project.Project,
                            Region = detail.Region,
                            RegionName = detail.RegionName,
                            Remark = project.Remark,
                            //SysArea = project.SysArea,
                            ScreeningPlanProjectId = project.Id,
                            ScreeningPlanProDetailId= detail.Id,
                            SearchMajorCode = detail.SearchMajorCode,
                            StandardID = detail.StandardID,
                            StandardContent = detail.StandardContent,
                            Type = detail.Type,
                            CreateFactory = detail.CreateFactory,
                            RiskLevel = detail.RiskLevel,
                            RiskLevelText = detail.RiskLevelText,

                        });
                    });
                });
            });
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(YH_ScreeningPlanController) + "_" + nameof(YH_ScreeningPlanController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> SaveAsync(YH_ScreeningPlanDto dto)
        {
            dto.NowTime = _service.ComputeRunTime(dto);
            dto.YH_ScreeningPlanTask = _service.CreateYH_ScreeningPlanTask(dto);
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                dto.IsProceed = true;
                dto.IsNotRemind = true;
                dto.CreateFactory = UserIdentity.Factory;
                await _service.InsertAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                await _service.UpdateForPCAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(YH_ScreeningPlanController) + "_" + nameof(YH_ScreeningPlanController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult> DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        [PermissionFilter(nameof(YH_ScreeningPlanController) + "_" + nameof(YH_ScreeningPlanController.Get), AuthorizationConst.GET)]
        public async Task<IActionResult> Get(Guid id)
        {
            var dto = await _service.GetAsync(id);
            if (dto == null) return this.JsonFaild("未找到对应数据:" + id);
            //拼接参与人员姓名
            var str = "";
            dto.YH_ScreeningPlanUser.ToList().ForEach(a =>
            {
                str += a.UserText + ",";
            });
            if (str.Length > 0)
                str = str.Substring(0, str.Length - 1);
            dto.Participant = str;

            dto.FrequencyText = _service.ShowFrequencyText(dto);

            dto.YH_ProjectAndDetail = new List<YH_ProjectAndDetail>();
            dto.YH_ScreeningPlanProject.ToList().ForEach(project =>
            {
                project.YH_ScreeningPlanProDetail.ToList().ForEach(detail =>
                {
                    detail.ScreeningPlanProDetailId = detail.Id;
                    dto.YH_ProjectAndDetail.Add(new YH_ProjectAndDetail()
                    {
                        Id = detail.Id,
                        ScreeningPlanId = dto.Id,
                        Project = project.Project,
                        Region = detail.Region,
                        RegionName = detail.RegionName,
                        AreaName = detail.RegionName,
                        Remark = project.Remark,
                        SysArea = project.SysArea,
                        ScreeningPlanProjectId = project.Id,
                        ScreeningPlanProDetailId = detail.Id,
                        SearchMajorCode = detail.SearchMajorCode,
                        StandardID = detail.StandardID,
                        StandardContent = detail.StandardContent,
                        Type = detail.Type,
                        CreateFactory = detail.CreateFactory,
                        RiskLevel = detail.RiskLevel,
                        RiskLevelText = detail.RiskLevelText
                    });
                });
            });
            //清空项目集（目的是提交页面时，该对象只传递需添加的项）
            //dto.YH_ScreeningPlanProject = null;
            return this.JsonSuccess(dto);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(YH_ScreeningPlanController) + "_" + nameof(YH_ScreeningPlanController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult> Export(PagingModel<YH_ScreeningPlanDto> pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion


    }
}
